//
//  SpecialTopicViewController.swift
//  TravelNotes
//
//  Created by 千锋 on 16/8/17.
//  Copyright © 2016年 胡光健. All rights reserved.
//

import UIKit

class SpecialTopicViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    var tableView = UITableView()
    var page = 1
    var dataArray = NSMutableArray()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        createUI()
        createRefresh()
    }

    func createRefresh() {
        self.tableView.header = MJRefreshNormalHeader(refreshingBlock: { () -> Void in
            self.page = 1
            self.dataArray.removeAllObjects()
            self.getData()
        })
        self.tableView.footer = MJRefreshAutoNormalFooter(refreshingBlock: { () -> Void in
            self.page += 1
            self.getData()
        })
        tableView.header.beginRefreshing()
    }
    
    func getData() {
        let manager = AFHTTPSessionManager()
        manager.GET("http://chanyouji.com/api/articles.json?page=\(page)", parameters: nil, success: { (dataTask: NSURLSessionDataTask?, resp: AnyObject?) -> Void in
            
            let array = resp as! NSArray
            for i in 0..<array.count {
                let dic = array[i]
                let specialTopicModel = SpecialTopicModel()
                specialTopicModel.setValuesForKeysWithDictionary(dic as! [String : AnyObject])
                self.dataArray.addObject(specialTopicModel)
            }
            if self.page == 1 {
                self.tableView.header.endRefreshing()
            }
            else {
                self.tableView.header.endRefreshing()
            }
            self.tableView.reloadData()
            }) { (dataTask: NSURLSessionDataTask?, error: ErrorType?) -> Void in
                print(error)
        }
    }
    
    func createUI() {
        tableView = UITableView(frame: CGRectMake(0, 0, screenWidth, screenHeight), style: .Plain)
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.view.addSubview(tableView)
        
        tableView.registerNib(UINib(nibName: "SpecialTopicCell", bundle: nil), forCellReuseIdentifier: "specialTopicCell")
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("specialTopicCell", forIndexPath: indexPath) as! SpecialTopicCell
        
        if  dataArray.count > 0 {
            cell.model = self.dataArray[indexPath.row] as! SpecialTopicModel
        }
        return cell
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 200
    }
}
